package com.myc.wx.controller;

import com.myc.wx.handler.WxChatMsgFactory;
import com.myc.wx.handler.WxChatMsgHandler;
import com.myc.wx.utils.MessageUtil;
import com.myc.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
public class CallBackController {

    private static final String token = "aassddffweeww";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    private String test(){
        return "登录查看";
    }

    /***
     * 回调消息校验
     * 与微信公众号互联
     * 填写url和token：
     *  url是natapp转发的http/callback
     *  token是上面的token  ---private static final String token = "aassddffweeww";
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /***
     * 回调消息校验
     */
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String requestBody ,
                           @RequestParam("signature") String signature ,
                           @RequestParam("timestamp") String timestamp ,
                           @RequestParam("nonce") String nonce ,
                           @RequestParam(value = "msg_signature" ,required = false) String msgSignature){
        log.info("接收到微信消息：requestBody：{}", requestBody);
        //定义个map接收消息体
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        //获取xml消息体中的msgType和event
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? "" : msgMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);
        //拼接一个枚举Key
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)){
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        //根据key获取对应的接口实现类
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)){
            return "unknown";
        }
        //调用具体的实现类返回
        String replyContent = wxChatMsgHandler.dealMsg(msgMap);
        log.info("replyContent:{}", replyContent);

        return replyContent;
    }
}
